package com.zuohuaipan.headine.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zuohuaipan.headine.R;
import com.zuohuaipan.headine.adapter.My_list_Adapter;
import com.zuohuaipan.headine.utils.Xutils_video_image;

import org.json.JSONException;
import org.json.JSONObject;

public class My_Fragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ImageView w_phone;
    private ImageView w_weibo;
    private ImageView w_weixin;
    private LinearLayout my_shoucang;
    private LinearLayout my_yejian;
    private LinearLayout my_shezhi;
    private ListView lv;
    private TextView m_text;

    private Tencent mTencent;
    private String App_ID = "1105924500";
    private IUiListener loginListener;
    private IUiListener userInfoListener;
    private IUiListener shareInfoListener;
    //获取权限列表。所有权限为 all
    private static String SCOPE = "all";


    public My_Fragment() {
        // Required empty public constructor
    }

    public static My_Fragment newInstance(String param1, String param2) {
        My_Fragment fragment = new My_Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_, container, false);
        //找到控件
        initView(view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //设置适配器
        setAdapter();
        //监听
        setonListener();
        //判断登录状态
        islogin();
        //初始化qq登录
        initQqLogin();


    }

    private void islogin() {
        SharedPreferences spf = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
        boolean b = spf.getBoolean("islogin", false);

        if (b) {
            w_phone.setVisibility(View.GONE);
            w_weibo.setVisibility(View.GONE);
            String qqname = spf.getString("qqname", "111");
            String qqimg = spf.getString("qqimg", "");
            Xutils_video_image.display(w_weixin, qqimg);
            m_text.setText(qqname);

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //判断登录状态
            islogin();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //判断登录状态
        islogin();
    }

    private void setAdapter() {
        My_list_Adapter my = new My_list_Adapter(getActivity());
        lv.setAdapter(my);
    }

    /**
     * 设置监听
     */
    public void setonListener() {
        w_phone.setOnClickListener(this);
        w_weibo.setOnClickListener(this);
        w_weixin.setOnClickListener(this);
        my_shoucang.setOnClickListener(this);
        my_yejian.setOnClickListener(this);
        my_shezhi.setOnClickListener(this);

    }

    private void initView(View view) {
        w_phone = (ImageView) view.findViewById(R.id.w_phone);
        w_weibo = (ImageView) view.findViewById(R.id.w_weibo);
        w_weixin = (ImageView) view.findViewById(R.id.w_weixin);
        my_shoucang = (LinearLayout) view.findViewById(R.id.my_shoucang);
        my_yejian = (LinearLayout) view.findViewById(R.id.my_yejian);
        my_shezhi = (LinearLayout) view.findViewById(R.id.my_shezhi);
        m_text = (TextView) view.findViewById(R.id.m_text);
        lv = (ListView) view.findViewById(R.id.m_listview);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.w_phone:
                mTencent.login(this, SCOPE, loginListener);
                break;
            case R.id.w_weibo:
                break;
            case R.id.w_weixin:
                break;
            case R.id.my_shoucang:
                break;
            case R.id.my_yejian:
                break;
            case R.id.my_shezhi:
                break;

        }
    }

    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        try {
            mTencent = Tencent.createInstance(App_ID, getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {

                //登录成功后回调该方法
                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                SharedPreferences spf = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = spf.edit();
                edit.putBoolean("islogin", true);
                edit.commit();


                //设置openid，如果不设置这一步的话无法获取用户信息
                JSONObject jo = (JSONObject) o;
                String openID;
                try {
                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
            }
        };
        //获取用户信息的回调接口
        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jo = (JSONObject) o;
                try {
                    JSONObject info = (JSONObject) o;
                    //获取用户具体信息
                    String nickName = info.getString("nickname");
                    String figureurl_qq_2 = info.getString("figureurl_qq_2");
                    w_phone.setVisibility(View.GONE);
                    w_weibo.setVisibility(View.GONE);
                    Xutils_video_image.display(w_weixin, figureurl_qq_2);
                    m_text.setText(nickName);

                    SharedPreferences sp = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit1 = sp.edit();
                    edit1.putString("qqname", nickName);
                    edit1.putString("qqimg", figureurl_qq_2);
                    edit1.commit();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };
    }

    //获取用户信息
    private void getUserInfo() {
        UserInfo info = new UserInfo(getActivity(), mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }

    //QQ登陆回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //判断登陆成功

        //QQ登陆回调
        // Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        //一定要加上，不然监听不起作用
        Tencent.handleResultData(data, loginListener);
        //获取用户信息
        getUserInfo();


    }
}
